<template>
  <div class="columns">
    <div class="column">
      <Author v-if="flag" :user="topicUser" />
    </div>
    <!-- 文章 -->
    <div class="column is-three-quarters">

      <!--主题-->
      <el-card class="box-card" shadow="never">
        <div slot="header" class="has-text-centered">
          <p class="is-size-5 has-text-weight-bold">{{ topic.title }}</p>
          <div class="has-text-grey is-size-7 mt-3">
            <span>
              {{ dayjs(topic.createTime).format("YYYY/MM/DD HH:mm:ss") }}
              <el-divider direction="vertical" />

              <span
                >{{ $t('post.author') }}：
                <router-link
                  :to="{
                    name: 'user',
                    params: { username: topicUser.username },
                  }"
                  >{{ topicUser.alias }}</router-link
                >
              </span>

              <el-divider direction="vertical" />
              <span>{{ $t('post.views') }}：{{ topic.view }}</span>
            </span>
          </div>
        </div>

        <!-- MarkDown-->
        <div id="preview" />
        <!-- <span>
            <a @click="()=>{{item.Supports+=1};addLikeNum(item.Id)}">
              <a-icon
                type="like-o"
                theme="twoTone"
                :two-tone-color="hasExisted(item.Id)?'#d32':''"
                style="margin-right:18px"
                @click="addLikeNum(item.Id)"
              />
              {{item.Supports}}
            </a>
          </span> -->

        <!--标签-->
        <nav class="level has-text-grey is-size-7 mt-6">
          <div class="level-left">
            <p class="level-item">
              <b-taglist>
                <span v-for="(tag, index) in tags" :key="index"
                  @click="search(tag.name)" style="cursor:pointer;">
                  {{ "#" + tag.name }}&nbsp;
                </span>
                
              </b-taglist>
            </p>
          </div>

          <!-- 点赞收藏功能 -->
          <button class="like" v-show="!liked" @click="liking(topic.id)"><i class="fa fa-thumbs-o-up"> </i> {{ $t('post.like') }}</button>
          <button class="liked" v-show="liked" @click="unliking(topic.id)"> {{ $t('post.starred') }}</button>

          <div class="level-right">
            <router-link
              v-if="token && user.id === topicUser.id" 
              class="level-item"
              :to="{ name: 'post-edit', params: { id: topic.id } }"
            >
              <span class="tag">{{ $t('post.edit') }}</span>
            </router-link>
            <a v-if="token && user.roleId == 1 || user.id === topicUser.id" class="level-item">
              <span class="tag" @click="handleDelete(topic.id)">{{ $t('post.del') }}</span>
            </a>
          </div>
        </nav>
      </el-card>
      <comment :slug="topic.id" /> 
    </div>
  </div>
</template>

<script>
import { getPost, deletePost } from "@/api/post";
import { mapGetters } from "vuex";
import Author from "@/view/post/Author";
import Comment from '@/component/Comment/Comment';
import Vditor from "vditor";
import "vditor/dist/index.css";
import { like, hasLiked, unLike } from '@/api/like'

export default {
  name: "TopicDetail",
  components: { Author, Comment },
  computed: {
    ...mapGetters(["token", "user"]),
  },
  data() {
    return {
      liked:false,
      clickedDate:[],
      flag: false,
      topic: {
        content: "",
        id: this.$route.params.id,
      },
      tags: [],
      topicUser: {},
    };
  },
  mounted() {
    this.fetchTopic();
    this.fetchInfo();
  },
  methods: {
    renderMarkdown(md) {
      Vditor.preview(document.getElementById("preview"), md, {
        hljs: {
          style: "github",
        },
      });
    },
    //初始化
    async fetchTopic() {
      getPost(this.$route.params.id).then((reponse) => {
        const { data } = reponse;
        document.title = data.topic.title;

        this.topic = data.topic;
        this.tags = data.tags;
        this.topicUser = data.user;
        this.comments = data.comments
        this.renderMarkdown(this.topic.content);
        this.flag = true;
      });
    },

    fetchInfo() {
    if(this.token != null && this.token !== '')
    {
      hasLiked(this.topic.id).then(value => {
        if (value.data != null) this.liked = true;
        else this.liked = false;
      })
    }
  },
    handleLike: function(id) {
    if(this.token != null && this.token !== '')
    {
      like(id).then(response => {
        const { message } = response
        this.$message.success(message)
        this.hasLiked = !this.hasLiked
        this.user.followerCount = parseInt(this.user.followerCount) + 1
      })
    }
    else{
      this.$message.error('请先登录')
      this.$router.push({ path: this.redirect || "/login" });
    }
  },
    handleunLike: function(id) {
      unLike(id).then(response => {
        const { message } = response
        this.$message.success(message)
        this.hasLiked = !this.hasLiked
        this.user.followerCount = parseInt(this.user.followerCount) - 1
      })
    },

    handleDelete(id) {
      deletePost(id).then((value) => {
        const { code, message } = value;
        if (code === 200) {
          this.$message.success(message);
          setTimeout(() => {
            this.$router.push({
              path: "/",
            });
          }, 500);
        }
      });
    },
    //like and star
    liking(id){
      this.liked = true;
      this.handleLike(id);
    },
    //cancel like
    unliking(id){
      this.liked = false;
      this.handleunLike(id);
    },
    search(tagName) {
      this.$router.push({ path: '/tag?key=' + encodeURIComponent(tagName.replace(/%/g, '%25')) })
    }
  },
};
</script>